package pers.lx.crm.service.info.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.lx.crm.base.common.pigeon.Result;
import pers.lx.crm.base.constant.ErrorConstant;
import pers.lx.crm.base.constant.KeyConstants;
import pers.lx.crm.base.util.ResultUtil;
import pers.lx.crm.dao.info.CustomerDao;
import pers.lx.crm.entiy.info.CustomerDO;
import pers.lx.crm.entiy.info.CustomerInfoDO;
import pers.lx.crm.service.info.CustomerService;

import java.util.List;

/**
 * Created by lx on 2017/3/7.
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Override
    public Result getCustomer(CustomerDO customerDO) {
        Result result = new Result();
        customerDO.setCustomerInfoDOs(customerDao.selectCustomerInfo(customerDO.getId()));
        result.addParam(KeyConstants.CUSTOMER, customerDO);
        return result;
    }

    @Override
    public Result getCustomers(CustomerDO customerDO) {
        Result result = new Result() ;
        try {
            customerDO.setList(customerDao.selectCustomerListPage(customerDO));
            return ResultUtil.getPageResult(customerDO,result) ;
        } catch (Exception e){
            e.printStackTrace();
            result.setError(ErrorConstant.UNKNOWN_ERROR);
        }
        return result;
    }

    @Transactional
    @Override
    public Result addCustomer(CustomerDO customerDO) {
        Result result = new Result();
        customerDao.insertCutomer(customerDO);
        return result;
    }

    @Transactional
    @Override
    public Result updateCustomer(CustomerDO customerDO) {
        Result result = new Result();
        customerDao.updateCustomer(customerDO);
        customerDao.deleteCustomerInfo(customerDO.getId());
        for (CustomerInfoDO customerInfoDO : customerDO.getCustomerInfoDOs()) {
            customerDao.insertCustomerInfo(customerInfoDO);
        }
        return result;
    }

    @Transactional
    @Override
    public Result deleteCustomer(List<CustomerDO> customerDOs) {
        Result result = new Result();
        for (CustomerDO customerDO : customerDOs) {
            customerDao.deleteCustomerInfo(customerDO.getId());
            customerDao.deleteCustomer(customerDO);
        }
        return result;
    }
}
